import React, { useEffect, useState, useRef } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import styles from './index.module.scss'
export default function NotFound() {
  const navigate = useNavigate()
  const [time, setTime] = useState(5)
  // 延时器引用
  const timerRef = useRef(null)
  useEffect(() => {
    // 1. 创建延时器
    timerRef.current = setTimeout(() => {
      if (time <= 1) {
        // 倒计时结束：关闭定时器，并跳转到首页
        clearTimeout(timerRef.current)
        navigate('/')
      } else {
        // 到计时未结束：秒数减一
        setTime(time - 1)
      }
    }, 1000)

    // 2. 组件销毁时要清理延时器
    return () => {
      clearTimeout(timerRef.current)
    }
  }, [time, navigate])
  return (
    <div className={styles.root}>
      <h1>对不起，你访问的内容不存在...</h1>
      <p>
        {time} 秒后，返回<Link to="/">首页</Link>
      </p>
    </div>
  )
}
